package com.jy.task.fileoper;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import com.hierynomus.smbj.SMBClient;
import com.hierynomus.smbj.SmbConfig;
import com.hierynomus.smbj.auth.AuthenticationContext;
import com.hierynomus.smbj.connection.Connection;
import com.hierynomus.smbj.session.Session;
import com.hierynomus.smbj.share.DiskShare;

public class Smb2Oper {

	private String ip = "";
	private String userName = "";
	private String psw = "";
	private String fileName = "";
	private static DiskShare share;
	private static SMBClient client;

	public Smb2Oper(String ip, String userName, String psw, String fileName) {

		this.ip = ip;
		this.userName = userName;
		this.fileName = fileName;
		this.psw = psw;
	}

	/**
	 * 判斷smb2 是否能连接
	 * 
	 * @return
	 */
	public boolean smb2Connect() {
		boolean result = false;
		// 设置超时时间(可选)
		SmbConfig config = SmbConfig.builder()
				.withTimeout(120, TimeUnit.SECONDS)
				.withTimeout(120, TimeUnit.SECONDS) // 超时设置读，写和Transact超时（默认为60秒）
				.withSoTimeout(180, TimeUnit.SECONDS) // Socket超时（默认为0秒）
				.build();

		// 如果不设置超时时间 SMBClient client = new SMBClient();
		client = new SMBClient();
		try {
			System.out.println(">>" + ip + "  " + userName);
			System.out.println(">>" + fileName + "  " + psw);
			Connection connection = client.connect(ip);
			AuthenticationContext ac = new AuthenticationContext(userName,
					psw.toCharArray(), ip);
			Session session = connection.authenticate(ac);
			share = (DiskShare) session.connectShare(fileName);
			if (share.isConnected()) {
				result = true;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

}
